import React, {useEffect, useState} from "react";
import {
    Button,
    Checkbox,
    Col,
    Form,
    Input,
    InputNumber,
    message,
    Modal,
    Radio,
    Row,
    Tooltip, Tree, TreeSelect,
} from 'antd';
import {handleTree, setTreeSelect} from "@/utils/Z.ts";

import styles from "./index.module.css";
import {QuestionCircleOutlined} from "@ant-design/icons";
import {addRole, getRole, updateRole} from "@/api/system/role.ts";
import {
    addMenu,
    listMenu,
    roleMenuTreeSelect,
    treeselect as menuTreeSelect, updateMenu
} from "@/api/system/menu.js";
import { globalMessage } from "@/utils/message";

// 定义组件的 props 类型
interface MyComponentProps {
    open: boolean;
    title?: string;
    OnCanCle: () => void;
    record:any;

}

const EditorMenuView: React.FC<MyComponentProps> = (props) => {
    const [form] = Form.useForm();
    // 表单的值
    const [formData, setFormData] = useState(props.record)
    const [menuOptions, setMenuOptions] = useState([]);


    function handleCancel() {
        props.OnCanCle()
    }

    useEffect(() => {
        console.log(props,'props')
        getTreeSelect();
        form.setFieldsValue({
            parentId: props.record?.parentId || 0,
            menuType: props.record?.menuType || "M",
            icon: props.record?.icon || "",
            menuName: props.record?.menuName || "",
            orderNum: props.record?.orderNum || 0,
            isFrame: props.record?.isFrame || "1",
            path: props.record?.path || '',
            component: props.record?.component || '',
            perms: props.record?.perms || '',
            query: props.record?.query || '',
            isCache: props.record?.isCache || "0",
            visible: props.record?.visible || "0",
            status: props.record?.status || "0"
        });
    }, [props.record]);
    const getTreeSelect = () => {
        listMenu().then((res:any) => {
            if (res?.code === 200) {
                const menu = [{value: 0, title: "主类目", children: []}];
                const obj = {
                    key: "menuId",
                    value: "menuId",
                    title: "menuName",
                };
                menu[0].children = handleTree(setTreeSelect(res.data, obj), "menuId");
                setMenuOptions([...menu]);
            }
        });
    };

    const onValuesChange = (changedValues:any, allValues:any):void => {
        if (props.record.menuId !== undefined) {

            setFormData(prevState => ({
                ...prevState,
                ...changedValues
            }));
        } else {
            setFormData(prevState => ({
                ...allValues
            }));
        }

    };
    const handleSubmit = () => {
        // 在提交前先进行表单验证
        form.validateFields().then(values => {
            if (props.record.menuId !== undefined) {
                updateMenu(formData).then((res:any) => {
                     globalMessage().warning(res.msg).then(r => {})
                    props.OnCanCle()
                });
            } else {
                addMenu(formData).then((res:any) => {
                     globalMessage().warning(res.msg).then(r => {})
                    props.OnCanCle()
                });
            }
        }).catch(errorInfo => {

            // 如果验证失败，则不执行提交操作
        });
    }




    return (
        <>
            <Modal
                forceRender
                open={props.open}
                title={props.title}
                footer={null}
                onCancel={() => {
                    props.OnCanCle()
                }}
            >
                <Form
                    form={form}
                    name="basic"
                    style={{maxWidth: 600}}
                    onValuesChange={onValuesChange}>
                    <Row gutter={10}>
                        <Col span={24}>
                            <Form.Item label="上级菜单" name="parentId" labelCol={{span: 4}}>
                                <TreeSelect
                                    defaultValue={formData.parentId}
                                    showSearch
                                    style={{width: '100%'}}
                                    dropdownStyle={{maxHeight: 400, overflow: 'auto'}}
                                    placeholder="请选择"
                                    treeDefaultExpandAll
                                    treeData={menuOptions}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={24}>
                            <Form.Item label="菜单类型" name="menuType" labelCol={{span: 4}}>
                                <Radio.Group value={formData.menuType}>
                                    <Radio value="M">目录</Radio>
                                    <Radio value="C">菜单</Radio>
                                    <Radio value="F">按钮</Radio>
                                </Radio.Group>
                            </Form.Item>
                        </Col>
                        {formData.menuType !== 'F' && (
                            <Col span={24}>
                                <Form.Item label="菜单图标" name="icon" labelCol={{span: 4,}}>
                                    <Input value={formData.icon}/>

                                </Form.Item>
                            </Col>
                        )}
                        <Col span={12}>
                            <Form.Item
                                label="菜单名称:"
                                name="menuName"
                                labelCol={{span: 8,}}
                                rules={[
                                    {required: true, message: '请输入菜单名称!'},
                                ]}
                            >
                                <Input value={formData.menuName}/>
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                label="显示排序"
                                name="orderNum"
                                labelCol={{span: 9,}}
                                rules={[
                                    {required: true, message: '请输入显示排序!'},
                                ]}
                            >
                                <InputNumber min={0} value={formData.orderNum}/>
                            </Form.Item>
                        </Col>
                        {formData.menuType !== 'F' && (
                            <Col span={12}>
                                <Form.Item
                                    label={<Tooltip title="选择是外链则路由地址需要以`http(s)://`开头"><QuestionCircleOutlined/>是否外链:</Tooltip>}
                                    name="isFrame"
                                    labelCol={{span: 8,}}

                                >
                                    <Radio.Group value={formData.isFrame} defaultValue={"1"}>
                                        <Radio value={"0"}>是</Radio>
                                        <Radio value={"1"}>否</Radio>
                                    </Radio.Group>
                                </Form.Item>
                            </Col>
                        )}
                        {formData.menuType !== 'F' && (
                            <Col span={12}>
                                <Form.Item
                                    labelCol={{span: 9,}}
                                    label={<Tooltip
                                        title="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头"><QuestionCircleOutlined/>路由地址</Tooltip>}
                                    name="path"
                                    rules={[
                                        {required: true, message: '请输入路由地址!'},
                                    ]}
                                >
                                    <Input value={formData.path}/>
                                </Form.Item>
                            </Col>
                        )}
                        {formData.menuType === 'C' && (
                            <Col span={12}>
                                <Form.Item
                                    labelCol={{span: 8,}}
                                    label={<Tooltip
                                        title="访问的组件路径，如：`system/user/index`，默认在`views`目录下"><QuestionCircleOutlined/>组件路径</Tooltip>}
                                    name="component"

                                >
                                    <Input value={formData.component}/>
                                </Form.Item>
                            </Col>
                        )}
                        {formData.menuType !== 'M' && (
                            <Col span={12}>
                                <Form.Item
                                    labelCol={{span: 9,}}
                                    label={<Tooltip
                                        title="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)"><QuestionCircleOutlined/>权限字符</Tooltip>}
                                    name="perms"
                                >
                                    <Input value={formData.perms}/>
                                </Form.Item>
                            </Col>
                        )}
                        {formData.menuType === 'C' && (
                            <Col span={12}>
                                <Form.Item
                                    labelCol={{span: 8,}}
                                    label={<Tooltip
                                        title="访问路由的默认传递参数，如：`{'id': 1, 'name': 'ry'}`"><QuestionCircleOutlined/>路由参数</Tooltip>}
                                    name="query"
                                >
                                    <Input value={formData.query}/>
                                </Form.Item>
                            </Col>
                        )}
                        {formData.menuType === 'C' && (
                            <Col span={12}>
                                <Form.Item
                                    labelCol={{span: 9,}}
                                    label={<Tooltip
                                        title="选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致"><QuestionCircleOutlined/>是否缓存</Tooltip>}
                                    name="isCache"
                                >
                                    <Radio.Group value={formData.isCache} defaultValue={"1"}>
                                        <Radio value={"0"}>缓存</Radio>
                                        <Radio value={"1"}>不缓存</Radio>
                                    </Radio.Group>
                                </Form.Item>
                            </Col>)}
                        {formData.menuType !== 'F' && (
                            <Col span={12}>
                                <Form.Item
                                    labelCol={{span: 8,}}
                                    label={<Tooltip
                                        title="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问"><QuestionCircleOutlined/>显示状态</Tooltip>}
                                    name="visible"
                                >
                                    <Radio.Group value={formData.visible} defaultValue={"0"}>
                                        <Radio value={"0"}>显示</Radio>
                                        <Radio value={"1"}>隐藏</Radio>
                                    </Radio.Group>
                                </Form.Item>
                            </Col>)}
                        <Col span={12}>
                            <Form.Item
                                labelCol={{span: 9,}}
                                label={<Tooltip title="选择停用则路由将不会出现在侧边栏，也不能被访问"><QuestionCircleOutlined/>菜单状态</Tooltip>}
                                name="status"
                            >
                                <Radio.Group value={formData.status} defaultValue={"0"}>
                                    <Radio value={"0"}>正常</Radio>
                                    <Radio value={"1"}>停用</Radio>
                                </Radio.Group>
                            </Form.Item>
                        </Col>

                        <Col span={24}>
                            <Form.Item
                                wrapperCol={{offset: 16, span: 8}}
                            >
                                <div className={styles.buttonClass}>
                                    <Button type="primary" htmlType="submit" onClick={handleSubmit}>确认</Button>
                                    <Button type="primary" onClick={handleCancel}>取消</Button>
                                </div>
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </Modal>

        </>
    )
};
export default EditorMenuView;
